import axios, { type AxiosRequestConfig, type AxiosResponse } from "axios";
import { useRouter } from "vue-router";

// 创建 Axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_API_BASE_URL, // 从环境变量中获取 API 基础 URL
	timeout: 5000, // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
	(config: AxiosRequestConfig) => {
		const token = localStorage.getItem("token");
		if (token) {
			config.headers.Authorization = `Bearer ${token}`;
		}
		return config;
	},
	(error) => {
		console.log(error);
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(response: AxiosResponse) => {
		return response.data;
	},
	(error) => {
		console.log("err" + error);
		if (error.response.status === 401) {
			const router = useRouter();
			router.push("/login");
		}
		return Promise.reject(error);
	}
);

export default service;
